package com.jblv.frame.common.fastdfs;

import com.google.gson.reflect.TypeToken;
import com.jblv.frame.common.fastdfs.fdfs.*;
import com.jblv.frame.common.fastdfs.image.CommonPictureSizeType;
import com.jblv.frame.common.fastdfs.image.PictureUtils;
import com.jblv.frame.common.utils.GsonUtils;
import com.jblv.frame.common.fastdfs.fdfs.*;
import org.apache.commons.lang3.StringUtils;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.StorageClient1;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.text.NumberFormat;
import java.util.*;

/**
 * @author happyonion.yangtao
 * @version 1.0
 * @title FastDfsUtils
 * @projectName jblv-frame
 * @packageName com.jblv.common.fastdfs
 * @description FastDfsUtils
 * @date Create at 2020/5/7 10:45
 * @since jdk1.8
 */



public class FastDfsUtils {
    public static final String PICTURE_FILE_TYPE_CN = "图片";
    public static final String COMMON_FILE_TYPE_CN = "文件";
    public static final String FILE_EXT_NAME = "FILE_EXT_NAME";
    public static final String FILE_NAME = "_FILE_NAME";
    public static final String HEIGHT = "_HEIGHT";
    public static final String WIDTH = "_WIDTH";
    public static String HTTP_FAST_SERVER = null;

    public FastDfsUtils() {
    }

    public static void close() {
        ConnectionPool.getConnectionPool().close();
    }

    public static List<FastResult> uploadFileList(List<Base64FileDTO> base64FileDTOs) {
        List<FastResult> list = new ArrayList();
        FastResult fastResult = null;
        Iterator var3 = base64FileDTOs.iterator();

        while(var3.hasNext()) {
            Base64FileDTO base64Dto = (Base64FileDTO)var3.next();
            fastResult = uploadFile(base64Dto);
            list.add(fastResult);
        }

        return list;
    }

    public static FastResult uploadFile(Base64FileDTO base64FileDTO) {
        FastResult fastResult = null;
        Map<String, String> nameValuePairMap = null;
        nameValuePairMap = new HashMap();
        nameValuePairMap.put("_FILE_NAME", base64FileDTO.getFileName());
        fastResult = uploadFile( Base64Coder.decode(base64FileDTO.getFileStr()), getFileNameExt(base64FileDTO.getFileName()), nameValuePairMap);
        fastResult.setFileName(base64FileDTO.getFileName());
        return fastResult;
    }

    public static String getFileNameExt(String fileName) {
        String ext = "";
        if (StringUtils.isNotEmpty(fileName.trim())) {
            int index = fileName.lastIndexOf(".") + 1;
            if (index > -1) {
                ext = fileName.substring(index);
            }
        }

        return ext;
    }

    public static String getFilePathById(String fileId) {
        try {
            if (StringUtils.isNotEmpty(fileId)) {
                if (!fileId.startsWith("http")) {
                    return getFastUrl() + getFilePathByFileId(fileId);
                }

                return fileId;
            }
        } catch (Exception var2) {
            var2.printStackTrace();
        }

        return "";
    }

    public static String getSubFilePathById(String fileId, String subName) {
        int lastIndex = fileId.lastIndexOf(".");
        fileId = fileId.substring(0, lastIndex) + subName + fileId.substring(lastIndex);
        return !fileId.startsWith("http") ? getFastUrl() + getFilePathByFileId(fileId) : fileId;
    }

    public static boolean validateFile(List<File> files, List<String> fileNames, long maxFileSize, String fileExts, boolean isContain, String fileType) throws MyException {
        boolean flag = false;

        for(int i = 0; i < files.size(); ++i) {
            flag = validateFile((File)files.get(i), (String)fileNames.get(i), maxFileSize, fileExts, isContain, fileType);
            if (!flag) {
                return flag;
            }
        }

        return flag;
    }

    public static boolean validateFile(File file, String fileName, long maxFileSize, String fileExts, boolean isContain, String fileType) throws MyException {
        if (file.length() > maxFileSize) {
            int max = (int)(maxFileSize / 1048576L);
            throw new MyException("请选择小于" + max + "M的" + fileType);
        } else {
            String fileExt = getFileNameExt(fileName);
            if (StringUtils.isNotEmpty(fileExt)) {
                fileExt = fileExt.toLowerCase();
            }

            if ((!isContain || fileExts.contains(fileExt)) && (isContain || !fileExts.contains(fileExt))) {
                return true;
            } else {
                throw new MyException("上传的" + fileType + "格式不符合要求！");
            }
        }
    }

    public static boolean validateFile(List<Base64FileDTO> fileDTOs, long maxFileSize, String fileExts, boolean isContain, String fileType) throws MyException {
        String fileExtName = null;
        if (fileDTOs != null && fileDTOs.size() > 0) {
            Iterator var7 = fileDTOs.iterator();

            while(var7.hasNext()) {
                Base64FileDTO base64FileDTO = (Base64FileDTO)var7.next();
                fileExtName = getFileNameExt(base64FileDTO.getFileName());
                if (!fileExts.contains(fileExtName.toLowerCase())) {
                    throw new MyException("上传的" + fileType + "格式不符合要求！");
                }

                BASE64Decoder decoder = new BASE64Decoder();

                try {
                    byte[] b = decoder.decodeBuffer(base64FileDTO.getFileStr());
                    if ((long)b.length > maxFileSize) {
                        int max = (int)(maxFileSize / 1048576L);
                        throw new MyException("请选择小于" + max + "M的" + fileType);
                    }
                } catch (IOException var12) {
                    var12.printStackTrace();
                }
            }
        }

        return false;
    }

    private static StorageClient1 getClient() {
        return ConnectionPool.getConnectionPool().checkout(10);
    }

    public static String getFastUrl() {
        if (null != HTTP_FAST_SERVER) {
            return HTTP_FAST_SERVER;
        } else {
            Class var0 = FastDfsUtils.class;
            synchronized(FastDfsUtils.class) {
                if (null == HTTP_FAST_SERVER) {
                    init();
                }
            }

            return HTTP_FAST_SERVER;
        }
    }

    private static void init() {
        ConnectionPool.getConnectionPool();
    }

    public static String uploadSubFile(String masterFileId, String prefixName, byte[] bytes, String subFileExtName, Map<String, String> nameValuePairMap) {
        NameValuePair[] metaList = null;
        if (nameValuePairMap != null && nameValuePairMap.size() > 0) {
            metaList = new NameValuePair[nameValuePairMap.size() + 1];
            int i = 1;
            metaList[0] = new NameValuePair("FILE_EXT_NAME", subFileExtName);

            Map.Entry entry;
            for(Iterator var7 = nameValuePairMap.entrySet().iterator(); var7.hasNext(); metaList[i++] = new NameValuePair((String)entry.getKey(), (String)entry.getValue())) {
                entry = (Map.Entry)var7.next();
            }
        } else {
            metaList = new NameValuePair[]{new NameValuePair("FILE_EXT_NAME", subFileExtName)};
        }

        StorageClient1 storageClient = getClient();
        String result = "";

        try {
            result = storageClient.upload_file1(masterFileId, prefixName, bytes, subFileExtName, metaList);
            ConnectionPool.getConnectionPool().checkin(storageClient);
        } catch (IOException var9) {
            ConnectionPool.getConnectionPool().drop(storageClient);
            var9.printStackTrace();
        } catch (MyException var10) {
            ConnectionPool.getConnectionPool().drop(storageClient);
            var10.printStackTrace();
        } catch (NullPointerException var11) {
            ConnectionPool.getConnectionPool().drop(storageClient);
            var11.printStackTrace();
        } catch (Exception var12) {
            ConnectionPool.getConnectionPool().drop(storageClient);
            var12.printStackTrace();
        }

        return result;
    }

    public static FastResult uploadFile(byte[] bytes, String fileExtName, Map<String, String> nameValuePairMap, boolean ifAsynZoom) {
        FastResult fastResult = new FastResult();
        NameValuePair[] metaList = new NameValuePair[0];

        try {
            metaList = getMetadata(nameValuePairMap, fileExtName);
        } catch (IOException var22) {
            var22.printStackTrace();
        } catch (MyException var23) {
            var23.printStackTrace();
        }

        StorageClient1 storageClient = getClient();
        String[] fileIds = null;

        try {
            fileIds = storageClient.upload_file(bytes, fileExtName, metaList);
            fastResult.setGroupName(fileIds[0]);
            fastResult.setFilePath(fileIds[0] + "/" + fileIds[1]);
            fastResult.setFileId(fileIds[0] + "/" + fileIds[1]);
            if (nameValuePairMap != null && nameValuePairMap.get("_FILE_NAME") != null) {
                fastResult.setFileName((String)nameValuePairMap.get("_FILE_NAME"));
            }

            fastResult.setSize(getSizeUnit((long)bytes.length));
            ConnectionPool.getConnectionPool().checkin(storageClient);
            fastResult.setFlag(true);
        } catch (IOException var17) {
            ConnectionPool.getConnectionPool().drop(storageClient);
            var17.printStackTrace();
        } catch (MyException var18) {
            ConnectionPool.getConnectionPool().drop(storageClient);
            var18.printStackTrace();
        } catch (NullPointerException var19) {
            ConnectionPool.getConnectionPool().drop(storageClient);
            var19.printStackTrace();
        } catch (Exception var20) {
            ConnectionPool.getConnectionPool().drop(storageClient);
            var20.printStackTrace();
        } finally {
            Object bytes1 = null;
        }

        if (ifAsynZoom) {
            PictureUtils.asynZoom(fastResult);
        }

        return fastResult;
    }

    public static FastResult uploadFile(byte[] bytes, String fileExtName, Map<String, String> nameValuePairMap) {
        return uploadFile(bytes, fileExtName, nameValuePairMap, true);
    }

    private static String getSizeUnit(long length) {
        Double size = null;
        NumberFormat ddf1 = NumberFormat.getNumberInstance();
        ddf1.setMaximumFractionDigits(2);
        if (length > 1048576L) {
            size = (double)length / 1048576.0D;
            return ddf1.format(size) + "M";
        } else if (length > 1024L) {
            size = (double)length / 1024.0D;
            return ddf1.format(size) + "KB";
        } else {
            return size + "B";
        }
    }

    public static FastResult uploadFile(InputStream is, String fileExtName, Map<String, String> nameValuePairMap) {
        FastResult fastResult = new FastResult();

        try {
            byte[] bytes = ByteToInputStream.input2byte(is);
            fastResult = uploadFile(bytes, fileExtName, nameValuePairMap);
        } catch (IOException var6) {
            var6.printStackTrace();
        }

        return fastResult;
    }

    public static FastResult uploadFile(String filePath, String fileExtName, Map<String, String> nameValuePairMap) {
        NameValuePair[] metaList = null;
        if (nameValuePairMap != null && nameValuePairMap.size() > 0) {
            metaList = new NameValuePair[nameValuePairMap.size() + 1];
        } else {
            metaList = new NameValuePair[1];
        }

        metaList[0] = new NameValuePair("FILE_EXT_NAME", fileExtName);
        if (nameValuePairMap != null && nameValuePairMap.size() > 0) {
            int i = 1;

            Map.Entry entry;
            for(Iterator var5 = nameValuePairMap.entrySet().iterator(); var5.hasNext(); metaList[i++] = new NameValuePair((String)entry.getKey(), (String)entry.getValue())) {
                entry = (Map.Entry)var5.next();
            }
        }

        String[] fileIds = null;
        StorageClient1 storageClient1 = getClient();

        try {
            fileIds = storageClient1.upload_file(filePath, fileExtName, metaList);
            ConnectionPool.getConnectionPool().checkin(storageClient1);
        } catch (IOException var7) {
            var7.printStackTrace();
            ConnectionPool.getConnectionPool().drop(storageClient1);
        } catch (MyException var8) {
            var8.printStackTrace();
            ConnectionPool.getConnectionPool().drop(storageClient1);
        } catch (NullPointerException var9) {
            ConnectionPool.getConnectionPool().drop(storageClient1);
            var9.printStackTrace();
        } catch (Exception var10) {
            ConnectionPool.getConnectionPool().drop(storageClient1);
            var10.printStackTrace();
        }

        FastResult fastResult = new FastResult();
        fastResult.setFileName(fileExtName);
        if (fileIds != null) {
            fastResult.setFlag(true);
            fastResult.setGroupName(fileIds[0]);
            fastResult.setFilePath(fileIds[1]);
            fastResult.setFileId(fileIds[0] + "/" + fileIds[1]);
        } else {
            fastResult.setFlag(false);
        }

        PictureUtils.asynZoom(fastResult);
        return fastResult;
    }

    public static List<FastResult> uploadFile(List<File> files, List<String> fileNames) {
        List<FastResult> result = new ArrayList();
        if (files != null) {
            for(int i = 0; i < files.size(); ++i) {
                File file = (File)files.get(i);
                Map<String, String> nameValuePairMap = new HashMap();
                nameValuePairMap.put("_FILE_NAME", fileNames.get(i));
                uploadFileWithInfo(fileNames, result, i, file, nameValuePairMap);
            }
        }

        return result;
    }

    public static List<FastResult> uploadPic(List<File> files, List<String> fileNames, List<Integer> heights, List<Integer> widths) {
        List<FastResult> result = new ArrayList();
        if (files != null) {
            for(int i = 0; i < files.size(); ++i) {
                File file = (File)files.get(i);
                Map<String, String> nameValuePairMap = new HashMap();
                nameValuePairMap.put("_FILE_NAME", fileNames.get(i));
                nameValuePairMap.put("_HEIGHT", ((Integer)heights.get(i)).toString());
                nameValuePairMap.put("_WIDTH", ((Integer)widths.get(i)).toString());
                uploadFileWithInfo(fileNames, result, i, file, nameValuePairMap);
            }
        }

        return result;
    }

    private static void uploadFileWithInfo(List<String> fileNames, List<FastResult> result, int i, File file, Map<String, String> nameValuePairMap) {
        try {
            FastResult fastResult = uploadFile((InputStream)(new FileInputStream(file)), getFileNameExt((String)fileNames.get(i)), nameValuePairMap);
            fastResult.setFileName((String)fileNames.get(i));
            fastResult.setFilePath(getFilePathById(fastResult.getFileId()));
            result.add(fastResult);
        } catch (FileNotFoundException var6) {
            var6.printStackTrace();
        }

    }

    private static LoadFile downFile(String groupName, String remoteFilename) {
        StorageClient1 storageClient1 = getClient();
        LoadFile loadFile = new LoadFile();

        try {
            byte[] result = storageClient1.download_file(groupName, remoteFilename);
            loadFile.setBytes(result);
            NameValuePair[] nameValuePairs = storageClient1.get_metadata(groupName, remoteFilename);
            Map<String, String> map = new HashMap();
            if (nameValuePairs != null && nameValuePairs.length > 0) {
                NameValuePair[] var7 = nameValuePairs;
                int var8 = nameValuePairs.length;

                for(int var9 = 0; var9 < var8; ++var9) {
                    NameValuePair pair = var7[var9];
                    map.put(pair.getName(), pair.getValue());
                }
            }

            loadFile.setNameValuePairMap(map);
            loadFile.setFlag(true);
            ConnectionPool.getConnectionPool().checkin(storageClient1);
        } catch (IOException var11) {
            loadFile.setFlag(false);
            ConnectionPool.getConnectionPool().drop(storageClient1);
            var11.printStackTrace();
        } catch (MyException var12) {
            loadFile.setFlag(false);
            ConnectionPool.getConnectionPool().drop(storageClient1);
            var12.printStackTrace();
        } catch (NullPointerException var13) {
            loadFile.setFlag(false);
            ConnectionPool.getConnectionPool().drop(storageClient1);
            var13.printStackTrace();
        } catch (Exception var14) {
            loadFile.setFlag(false);
            ConnectionPool.getConnectionPool().drop(storageClient1);
            var14.printStackTrace();
        }

        return loadFile;
    }

    public static LoadFile downFile(String fileId) {
        int index = fileId.indexOf("/");
        String groupName = fileId.substring(0, index);
        String filePath = fileId.substring(index + 1);
        return downFile(groupName, filePath);
    }

    public static boolean deleteFile(String fileId) throws IOException, MyException {
        int index = fileId.indexOf("/");
        String groupName = fileId.substring(0, index);
        String remoteFilename = fileId.substring(index + 1);
        return deleteFile(groupName, remoteFilename);
    }

    public static boolean deleteFile(String groupName, String remoteFilename) {
        int i = 1;
        StorageClient1 storageClient1 = getClient();

        try {
            i = storageClient1.delete_file(groupName, remoteFilename);
            ConnectionPool.getConnectionPool().checkin(storageClient1);
        } catch (IOException var5) {
            ConnectionPool.getConnectionPool().drop(storageClient1);
            var5.printStackTrace();
        } catch (MyException var6) {
            ConnectionPool.getConnectionPool().drop(storageClient1);
            var6.printStackTrace();
        } catch (NullPointerException var7) {
            ConnectionPool.getConnectionPool().drop(storageClient1);
            var7.printStackTrace();
        } catch (Exception var8) {
            ConnectionPool.getConnectionPool().drop(storageClient1);
            var8.printStackTrace();
        }

        return i == 0;
    }

    private static NameValuePair[] getMetadata(Map<String, String> nameValuePairMap, String fileExtName) throws IOException, MyException {
        NameValuePair[] metaList = null;
        if (nameValuePairMap != null && nameValuePairMap.size() > 0) {
            metaList = new NameValuePair[nameValuePairMap.size() + 1];
            int i = 1;
            metaList[0] = new NameValuePair("FILE_EXT_NAME", fileExtName);

            Map.Entry entry;
            for(Iterator var4 = nameValuePairMap.entrySet().iterator(); var4.hasNext(); metaList[i++] = new NameValuePair((String)entry.getKey(), (String)entry.getValue())) {
                entry = (Map.Entry)var4.next();
            }
        } else {
            metaList = new NameValuePair[]{new NameValuePair("FILE_EXT_NAME", fileExtName)};
        }

        return metaList;
    }

    private static String getFilePathByFileId(String fileId) {
        return fileId;
    }

    public static List<FastResult> getFilesByIds(String filedIds) {
        List<FastResult> list = new ArrayList();
        if (!StringUtils.isEmpty(filedIds) && !"[]".equals(filedIds)) {
            String[] filedArray = filedIds.split(",");

            for(int i = 0; i < filedArray.length; ++i) {
                FastResult result = new FastResult();
                result.setFileId(filedArray[i]);
                result.setFilePath(getRealUrlContent(getFilePathByFileId(filedArray[i])));
                list.add(result);
            }

            return list;
        } else {
            return list;
        }
    }

    public static String getFilePathesByIds(String filedIds) {
        StringBuilder filePathesBuilder = new StringBuilder();
        if (StringUtils.isNotEmpty(filedIds)) {
            List<FastResult> resultList = getFilesByIds(filedIds);
            FastResult result;
            if (resultList != null) {
                for(Iterator var3 = resultList.iterator(); var3.hasNext(); filePathesBuilder.append(result.getFilePath())) {
                    result = (FastResult)var3.next();
                    if (filePathesBuilder.length() > 0) {
                        filePathesBuilder.append(",");
                    }
                }
            }
        }

        return filePathesBuilder.toString();
    }

    public static List<FastResult> getPicByFilesId(String filedIds, CommonPictureSizeType originalSizeType, CommonPictureSizeType listSizeType) {
        if (!StringUtils.isEmpty(filedIds) && !"[]".equals(filedIds)) {
            List<FastResult> list = new ArrayList();
            if (!StringUtils.isEmpty(filedIds) && !"[]".equals(filedIds)) {
                String[] filedArray = filedIds.split(",");

                for(int i = 0; i < filedArray.length; ++i) {
                    FastResult result = new FastResult();
                    result.setFilePath(getSubFilePath(filedArray[i], listSizeType));
                    result.setFileId(getSubFilePath(filedArray[i], originalSizeType));
                    list.add(result);
                }

                return list;
            } else {
                return list;
            }
        } else {
            return null;
        }
    }

    public static List<FastResult> getSubFilesByIds(String filedIds, CommonPictureSizeType sizeType) {
        List<FastResult> list = new ArrayList();
        if (!StringUtils.isEmpty(filedIds) && !"[]".equals(filedIds)) {
            String[] filedArray = filedIds.split(",");

            for(int i = 0; i < filedArray.length; ++i) {
                FastResult result = new FastResult();
                result.setFilePath(getSubFilePath(filedArray[i], sizeType));
                result.setFileId(getSubFilePath(filedArray[i], CommonPictureSizeType.SIZE_4_3));
                list.add(result);
            }

            return list;
        } else {
            return list;
        }
    }

    public static void main(String[] args) {
        FastResult result;
        try {
            FileInputStream in = new FileInputStream(new File("D:/1.jpg"));
            result = uploadFile((InputStream)in, "jpg", (Map)null);
            System.out.println("上传文件测试(文件流)");
            System.out.println(result.getFileId());
            System.out.println(result.getFilePath());
            System.out.println(getFilePathById(result.getFileId()));
        } catch (FileNotFoundException var6) {
            var6.printStackTrace();
        }

        try {
            result = uploadFile((String)"D:/1.txt", "txt", (Map)null);
            System.out.println("上传文件测试(文件路径)");
            System.out.println(result.getFileId());
            System.out.println(result.getFilePath());
            System.out.println(getFilePathById(result.getFileId()));
        } catch (Exception var5) {
        }

        try {
            if (null != downFile("group1/M00/05/B0/wKjLQ1tRXEeAACPiAAAABIwNizU295.txt")) {
                System.out.println("文件下载成功");
            } else {
                System.out.println("文件下载失败");
            }
        } catch (Exception var4) {
            var4.printStackTrace();
        }

        try {
            if (null != downFile("group1", "M00/05/B0/wKjLQ1tRXEeAACPiAAAABIwNizU295.txt")) {
                System.out.println("文件下载成功");
            } else {
                System.out.println("文件下载失败");
            }
        } catch (Exception var3) {
            var3.printStackTrace();
        }

    }

    public static String getRealUrlContent(String filePath) {
        return getFastUrl() + filePath;
    }

    public static String getTagedUrlContent(String filePath) {
        return filePath.startsWith(getFastUrl()) ? filePath.substring(getFastUrl().length()) : filePath;
    }

    public static String getSubFileId(String parentFileId, String subName) {
        if (StringUtils.isEmpty(parentFileId)) {
            return null;
        } else {
            int index = parentFileId.lastIndexOf(".");
            String fileId = parentFileId.substring(0, index) + subName + parentFileId.substring(index, parentFileId.length());
            return fileId;
        }
    }

    public static String getSubFilePath(String parentFileId, CommonPictureSizeType sizeType) {
        return getFilePathById(getSubFileId(parentFileId, sizeType.getSizeName()));
    }

    public static FastResult reUploadFile(String fileId) {
        LoadFile file = downFile(fileId);
        if (file == null) {
            return null;
        } else {
            FastResult result = uploadFile(file.getBytes(), (String)file.getNameValuePairMap().get("FILE_EXT_NAME"), file.getNameValuePairMap());
            return result;
        }
    }

    public static List<FastResult> reUploadFileList(String fileAryId) {
        if (StringUtils.isEmpty(fileAryId)) {
            return null;
        } else {
            List<FastResult> resultList = (List) GsonUtils.jsonToBean(fileAryId, (new TypeToken<List<FastResult>>() {
            }).getType());
            if (resultList == null) {
                return null;
            } else {
                List<FastResult> newResultList = new ArrayList();
                Iterator var3 = resultList.iterator();

                while(var3.hasNext()) {
                    FastResult fastResult = (FastResult)var3.next();
                    newResultList.add(reUploadFile(fastResult.getFileId()));
                }

                return newResultList;
            }
        }
    }
}

